#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tornado.web
import datetime
import random
import re
import cgi
import core
import pymongo

from tornado.options import options

class BaseHandler(tornado.web.RequestHandler):
    def initialize(self):
        self.bcore = pymongo.Connection().bcore
        opt = {}
        opt['nowdate'] = self.nowdate
        opt['nowtime'] = self.nowtime
        opt['cats'] = self.bcore.cats.find()
        opt['images'] = self.bcore.files.find() # models.Files().news()
        opt['_options'] = core.options().site_options()
        opt['links'] = self.bcore.options.find({"type":"link"})
        profile = self.bcore.options.find({"type":"profile"})[0] #models.Profile().get()
        profile = profile and profile["val"] or "something..."
        opt['profile'] = core.text().transfer(profile)
        self.opt = opt

    @property
    def nowdate(self):
        return str(datetime.datetime.now()).split(" ")[0]
    
    @property
    def nowtime(self):
        return str(datetime.datetime.now()).split(".")[0]

class MainHandler(BaseHandler):
    def get(self,args):
        if args:
            page = int(args)
        else:
            page = 1
            
        start,end = (page-1)*options.page_limit,options.page_limit

        opt = self.opt
        opt['posts'] = {}
        opt['posts']['rowset'] = self.bcore.posts.find({"status":"publish"}).sort([("top",pymongo.DESCENDING),("ctime",pymongo.DESCENDING)])[start:start+end]
        opt['posts']['page'] = page
        opt['posts']['url'] = "/p/"
        self.render("index.html",re=re,**opt)

class CateHandler(BaseHandler):
    def get(self,args):
        cate,page = args.split("/")
        if page:
            page = int(page)
        else:
            page = 1
        start,end = (page-1)*options.page_limit,options.page_limit
        opt = self.opt
        
        opt['posts'] = {}
        opt['posts']['rowset'] = self.bcore.posts.find({"cats":cate,"status":"publish"})[start:start+end]
        opt['posts']['page'] = page
        opt['posts']['url'] = "/c/%s/" % (cate)
        self.render("index.html",re=re,**opt)
        

class ShowHandler(BaseHandler):
    def get(self,args):
        opt = self.opt 
        opt["post"] = self.bcore.posts.find_one({"title":args})
        
        content = core.text().transfer(opt["post"]["content"])

        opt["post"]["content"] = content
        self.render("post.html",**opt)
